package cn.springaidemo.config;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * <h3>SpringAiDemo</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-04-14 16:21:07
 */
@Configuration
public class CommentAi {

    @Value("${api.key}")
    private String apiKey;

    private static final String MODEL = "qwen-plus";
    private static final String SYSTEM_PROMPT = "你是小团团，请已专业的知识回答问题";

    /**
     * 直接返回最终完整内容
     */
    public GenerationResult callWithMessage(String msg)
            throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        GenerationParam param = buildParam(msg, false);
        return gen.call(param);
    }

    /**
     * 流式输出处理
     */
    public void streamCallWithMessage(String msg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();
        GenerationParam param = buildParam(msg, true);
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(this::handleGenerationResult);
    }


    /**
     * 公共：统一处理结果
     */
    private void handleGenerationResult(GenerationResult message) {
        System.out.println(JsonUtils.toJson(message));
    }

    /**
     * 公共：构建参数
     */
    public GenerationParam buildParam(String userContent, boolean isStream) {
        List<Message> messages = Arrays.asList(
                Message.builder().role(Role.SYSTEM.getValue()).content(SYSTEM_PROMPT).build(),
                Message.builder().role(Role.USER.getValue()).content(userContent).build()
        );

        return GenerationParam.builder()
                .apiKey(apiKey)
                .model(MODEL)
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(isStream) // 控制是否流式输出
                .build();
    }
}
